<template>
  <view class="page-box" :class="{'page-no-btn': loading}">
    <AIHeader @update:data="getIsMessage" @on-select="handleSlectModel" :modelList="modelList"/>

    <!-- 左侧弹出层 -->
    <view class="left-message">
      <uv-popup ref="leftPopup" mode="left" :custom-style="{ width: '80%', height: '100%' }"
                :overlay-style="{ backgroundColor: 'rgba(0, 0, 0, 0.1)' }" @change="onPopupChange">
        <view class="message-box">
          <!-- 顶部历史对话 -->
          <scroll-view class="message-top" scroll-y="true" :enable-back-to-top="true">
            <view class="message-list">
              <view class="message-title">今天</view>
              <view class="message-content" v-for="item in chatList" :key="item.sessionId"
                   :class="{ active: item.sessionId == currentSessionId }">
                <text @click="handleOpenChat(item.sessionId)">{{ item.title }}</text>
                <view v-if="item.select" class="edit-input">
                  <uv-input v-model="text" placeholder="" :class="isInput ? 'isFocus' : ''"
                           ref="myField" :focus="true" @blur="inputBlur"
                           :maxlength="50"/>
                </view>
 <!--               <uv-popover :actions="actions" @select="onSelect(item,0)">
                  <template #reference>
                    <uv-icon v-show="!isInput" name="more-dot-fill"/>
                  </template>
                </uv-popover> -->
              </view>
            </view>

            <view class="message-list" v-if="lastList.length">
              <view class="message-title">昨天</view>
              <view class="message-content" v-for="item in lastList" :key="item.sessionId"
                   :class="{ active: item.sessionId == currentSessionId }">
                <text @click="handleOpenChat(item.sessionId)">{{ item.title }}</text>
                <view v-if="item.select" class="edit-input">
                  <uv-input v-model="text" placeholder="" :class="isInput ? 'isFocus' : ''"
                           ref="myField" :focus="true" @blur="inputBlur"
                           :maxlength="50"/>
                </view>
<!--                <uv-popover :actions="actions" @select="onSelect(item,1)">
                  <template #reference>
                    <uv-icon v-show="!isInput" name="more-dot-fill"/>
                  </template>
                </uv-popover> -->
              </view>
            </view>

            <view class="message-list" v-if="recentList.length">
              <view class="message-title">前七天</view>
              <view class="message-content" v-for="item in recentList" :key="item.sessionId"
                   :class="{ active: item.sessionId == currentSessionId }">
                <text @click="handleOpenChat(item.sessionId)">{{ item.title }}</text>
                <view v-if="item.select" class="edit-input">
                  <uv-input v-model="text" placeholder="" :class="isInput ? 'isFocus' : ''"
                           ref="myField" :focus="true" @blur="inputBlur"
                           :maxlength="50"/>
                </view>
<!--                <uv-popover :actions="actions" @select="onSelect(item,2)">
                  <template #reference>
                    <uv-icon v-show="!isInput" name="more-dot-fill"/>
                  </template>
                </uv-popover> -->
              </view>
            </view>
          </scroll-view>

          <!-- 底部用户设置 -->
          <view class="setup-bot">
<!--            <uv-popover ref="setupPopover" :show-arrow="false" placement="top-start" @change="onSetupChange">
              <view class="setup-box">
                <view class="box-list">
                  <uv-icon name="setting" size="20"/>
                  <view class="setup-name">系统设置</view>
                </view>
                <view class="box-list" @click="deleAllChat">
                  <uv-icon name="trash" size="20"/>
                  <view class="setup-name">删除所有会话</view>
                </view>
                <view class="box-list">
                  <uv-icon name="account" size="20"/>
                  <view class="setup-name">联系我们</view>
                </view>
                <view class="box-list" @click="feedBack">
                  <uv-icon name="edit-pen" size="20"/>
                  <view class="setup-name">意见反馈</view>
                </view>
              </view>
              <template #reference>
                <view class="setup-bot-box" @click="toggleSetup">
                  <view class="setup-userHeadImg">
                    <image v-if="userInfo.avatar" :src="userInfo.avatar" alt=""/>
                    <uv-icon v-else size="24" color="#ddd" name="account"/>
                  </view>
                  <view class="setup-userName">
                    <text class="nickname-text">{{ userInfo.username || '' }}</text>
                  </view>
                </view>
              </template>
            </uv-popover>
         -->

          </view>
        </view>
      </uv-popup>
    </view>

    <!-- 会话列表 -->
    <scroll-view 
      class="ai-content" 
      ref="chatContent" 
      scroll-y="true" 
      :scroll-top="scrollTop"
      :enable-back-to-top="true"
      :scroll-with-animation="true"
    >
      <AIMessage v-for="(item, index) in messages" :key="index" :role="item.isSelf ? 'user' : 'assistant'"
                 :message="item">
      </AIMessage>
      <view class="s-dialog" v-if="messages.length && isDoneInput">
        <uv-button @click="openDialog()" color="rgba(114, 50, 221,.9)" size="small"
                   icon="chat" shape="circle" type="primary">
          开启新对话
        </uv-button>
      </view>
    </scroll-view>

    <!-- 底部输入 -->
    <view class="ai-footer">
      <view class="short-buttons" v-if="!loading">
        <AIButton v-for="(item, index) in btnList" :text="item" :key="index" size="small"
                  @click="handleChoose(item)">
        </AIButton>
      </view>
      <view class="ai-chat-composer">
        <uv-input class="composer-core" v-if="isDoneInput" v-model="userInput" type="textarea"
                  placeholder="输入币种名称分析" :auto-height="true" :maxlength="500"
                  @keyboardheightchange="onKeyboardHeightChange">
          <template #suffix>
            <uv-icon v-if="userInput.length > 0" name="arrow-up-fill"
                     color="#4facfe" size="30" @click="sendMessage"/>
          </template>
        </uv-input>
        <uv-input class="composer-core" v-else type="textarea"
                  placeholder="分析中，预计30s，请稍后" :disabled="true"/>
      </view>
    </view>
  </view>
</template>

<script>
import AIHeader from './components/ai-header.vue'
import AIButton from './components/ai-button.vue'
import AIMessage from './components/ai-message.vue'
import { createSessionid, delAllChat, delChat, getChatHistory, getChatList, getModelList } from '@/api/ai'
import { mapGetters } from 'vuex'

export default {
  components: {
    AIHeader,
    AIMessage,
    AIButton,
  },
  computed: {
    ...mapGetters('user', ['userInfo'])
  },
  onLoad(options) {
    const symbol = options.symbol
    console.log('symbol', symbol)
    // 从推荐过来
    if (symbol) {
      this.scrollToBottom()
      createSessionid({
        subModelId: 16,
        forceNewSession: false,
      }).then((res) => {
        if (res.code === 20000) {
          this.currentSessionId = res.data
          this.init(symbol)
        }
      })
    } else {
      this.init(symbol)
    }
  },
  data() {
    return {
      recentList: [],
      lastList: [],
      chatList: [],
      currentSessionId: '',
      currentModel: {},
      isMessage: false,
      isSetup: false,
      isInput: false,
      actions: [
        { text: '删除', icon: 'trash', color: 'red' },
      ],
      userInput: '',
      messages: [],
      loading: false,
      response: null,
      btnList: [
        '1小时BTC',
        '1小时ETH',
        '4小时BTC',
        '4小时ETH',
        '8小时BTC',
        '8小时ETH',
        '1日BTC',
        '1日ETH',
      ],
      text: '今天天气怎么样',
      modelList: [],
      isDoneInput: true,
      scrollTop: 0,
    }
  },
  methods: {
    // 删除所有会话
    deleAllChat() {
      uni.showModal({
        title: '提示',
        content: '是否删除所有会话？',
        success: (res) => {
          if (res.confirm) {
            this.handleDelAll()
          }
        }
      })
    },

    // 获取用户信息
    init(symbol) {
      this.getModel()
      this.getChatList()
      console.log('symbol1111', symbol)
      symbol && this.sendMessage('', symbol)
    },

    handleOpenChat(sessionId) {
      this.getChatHistory(sessionId)
    },

    scrollToBottom() {
      this.$nextTick(() => {
        this.scrollTop = 999999
      })
    },

    handleSlectModel(item) {
      this.currentModel = item
      console.log('handleSlectModel', item)
    },

    getChatHistory(sessionId) {
      this.isMessage = false
      this.messages = []
      getChatHistory({
        sessionId,
      }).then((res) => {
        if (res.code === 20000) {
          this.currentSessionId = sessionId
          this.messages = res.data.map(item => {
            return {
              loading: false,
              msgType: 'text',
              isSelf: false,
              time: item.questionTime,
              mid: item.answerId,
              text: item.answerContent,
            }
          })
          this.scrollToBottom()
        }
      })
    },

    // 创建新会话
    openDialog() {
      this.messages = []
      this.createSession()
    },

    createSession() {
      createSessionid({
        subModelId: 16,
        forceNewSession: false,
      }).then((res) => {
        if (res.code === 20000) {
          this.currentSessionId = res.data
          console.log('currentSessionId', res.data)
        }
      })
    },

    // 模型列表
    getModel() {
      getModelList().then((res) => {
        if (res.code === 20000) {
          this.modelList = [{
            "mainModelId": 1,
            "mainModelName": "DeepSeek-V3",
            "mainModelDescription": "DeepSeek满血版",
            "mainModelImg": 'https://www.aiaabiok.com/imgsh5/img/deepseek1.png',
          }, {
            "mainModelId": 2,
            "mainModelName": "GPT-4",
            "mainModelDescription": "OpenAI最新大模型",
            "mainModelImg": "https://www.aiaabiok.com/imgsh5/img/openai1.png",
          }, {
            "mainModelId": 3,
            "mainModelName": "SILICON_FLOW",
            "mainModelDescription": "硅基流动最新模型",
            "mainModelImg": "https://www.aiaabiok.com/imgsh5/img/siliconflow1.png",
          }, {
            "mainModelId": 4,
            "mainModelName": "文心一言",
            "mainModelDescription": "古文理解与生成的智能模型",
            "mainModelImg": "https://www.aiaabiok.com/imgsh5/img/wxyy1.png",
          }]
          this.currentModel = this.modelList[0]
          this.createSession()
        }
      })
    },

    // 会话列表
    getChatList() {
      getChatList().then((res) => {
        if (res.code === 20000) {
          console.log('getChatList', res)
          const { today = [], lastDay = [], recent7 = [] } = res.data
          today.forEach((item) => {
            item.select = false
          })
          lastDay.forEach((item) => {
            item.select = false
          })
          recent7.forEach((item) => {
            item.select = false
          })
          this.chatList = today
          this.lastList = lastDay
          this.recentList = recent7
        }
      })
    },

    // 删除会话，支持批量
    delChat(sessionId, index) {
      uni.showLoading({
        title: '删除中...',
      })
      delChat({
        sessionId,
      }).then((res) => {
        if (res.code === 20000) {
          uni.hideLoading()
          // 今天
          if (index == 0) {
            const idx = this.chatList.findIndex((item) => item.sessionId == sessionId)
            if (idx !== -1) {
              this.chatList.splice(idx, 1)
            }
          }
          // 昨天
          if (index == 1) {
            const idx = this.lastList.findIndex((item) => item.sessionId == sessionId)
            if (idx !== -1) {
              this.lastList.splice(idx, 1)
            }
          }
          // 近七日
          if (index == 2) {
            const idx = this.recentList.findIndex((item) => item.sessionId == sessionId)
            if (idx !== -1) {
              this.recentList.splice(idx, 1)
            }
          }
        }
      })
    },

    // 获取点击展开侧边层事件
    getIsMessage(item) {
      console.log('===getIsMessage=', item)
      if (item) {
        this.getChatList()
        this.$refs.leftPopup.open()
      } else {
        this.$refs.leftPopup.close()
      }
      this.isMessage = item
    },

    // popup状态变化
    onPopupChange(e) {
      this.isMessage = e.show
    },

    // 昨天 前天历史记录选项选择后
    onSelect(item, index) {
      console.log('删除', item.sessionId)
      this.delChat(item.sessionId, index)
    },

    // 跳转到反馈页面
    feedBack() {
      uni.navigateTo({ url: '/subPages/ai/feedback' })
    },

    // 删除所有会话
    handleDelAll() {
      delAllChat().then(res => {
        if (res.code === 20000) {
          uni.showToast({
            title: '删除成功',
            icon: 'none'
          })
          this.getChatList()
        }
      })
    },

    inputBlur() {
      this.isInput = false
      console.log(1111, this.isInput)
    },

    handleChoose(text) {
      if (this.loading) {
        return uni.showToast({
          title: 'AI正在分析，请稍后',
          icon: 'none'
        })
      }
      this.sendMessage('', text)
    },

    onKeyboardHeightChange(e) {
      console.log('键盘高度变化', e)
      this.scrollToBottom()
    },

    toggleSetup() {
      if (this.isSetup) {
        this.$refs.setupPopover.close()
      } else {
        this.$refs.setupPopover.open()
      }
    },

    onSetupChange(e) {
      this.isSetup = e.show
    },

    async sendMessage(e, symbol) {
      this.scrollToBottom()
      this.isDoneInput = false
      e && e.preventDefault()
      const userInput = symbol || this.userInput
      console.log('userInput', userInput)
      console.log('loading', this.loading)
      if (!userInput || this.loading) return
      console.log(999999999)
      this.loading = true
      this.response = null // 清空上一条消息

      // 构造请求的body数据
      const data = {
        userInput, // 输入的消息
        maxTokens: 10, // 最大返回token数
        subModelId: 16,
        sessionId: this.currentSessionId,
      }
      console.log('currentSessionId11111', data)

      // 添加用户消息到消息列表
      this.messages.push({
        loading: false,
        msgType: 'text',
        isSelf: true,
        time: new Date().getTime(),
        mid: new Date().getTime(),
        text: userInput,
      })

      // 添加一个空的AI回复消息
      const aiMessageId = new Date().getTime() + 1
      this.messages.push({
        loading: true,
        msgType: 'text',
        isSelf: false,
        time: new Date().getTime(),
        mid: aiMessageId,
        text: '',
      })
      this.scrollToBottom()
      this.userInput = ''

      // 发出请求
      try {
        // 根据平台判断 URL
        // #ifdef H5
        const apiUrl = '/prod-api/data-analysis-api/chat/chatWithAi'
        // #endif
        // #ifndef H5
        const apiUrl = 'https://ht.aiaabiok.com/prod-api/data-analysis-api/chat/chatWithAi'
        // #endif
        
        const response = await uni.request({
          url: apiUrl,
          method: 'POST',
          header: {
            'Content-Type': 'application/json',
            'Authorization': this.$store.getters['user/token'] || '',
          },
          data: data,
          responseType: 'text'
        })

        if (response.statusCode !== 200) {
          console.error('请求失败，状态码:', response.statusCode)
          // 清除用户信息并跳转登录
          this.$store.commit('user/CLEAR_USER_INFO')
          this.$store.commit('token/CLEAR_TOKEN')
          uni.showToast({
            title: '登录已失效，请重新登录',
            icon: 'none',
            duration: 2000
          })
          setTimeout(() => {
            uni.reLaunch({ url: '/subPages/auth/login' })
          }, 2000)
          throw new Error(`HTTP error! status: ${response.statusCode}`)
        }

        // 处理流式响应
        let aiResponse = ''
        const lines = response.data.split('\n')

        for (const line of lines) {
          if (line && line.startsWith('data:')) {
            const jsonData = line.slice(11).trim()
            if (jsonData === '[DONE]') {
              this.loading = false
              this.isDoneInput = true
              const message = this.messages.find(msg => msg.mid === aiMessageId)
              if (message) {
                message.loading = false
                this.scrollToBottom()
              }
              break
            }

            try {
              const parsedData = JSON.parse(jsonData)
              if (parsedData.choices && parsedData.choices[0]) {
                const content = parsedData.choices[0].delta?.content || ''
                aiResponse += content
                console.log('aiResponse', aiResponse)
                // 更新AI回复消息
                const message = this.messages.find(msg => msg.mid === aiMessageId)
                if (message) {
                  message.text = aiResponse
                  this.scrollToBottom()
                }
              }
            } catch (e) {
              console.error('Error parsing SSE data:', e)
            }
          }
        }

        this.loading = false
        this.response = aiResponse
        this.isDoneInput = true
      } catch (error) {
        console.error('Error in sendMessage:', error)
        this.loading = false
        this.response = '请求失败，请重试！'

        // 更新错误消息
        const aiMessage = this.messages.find(msg => msg.mid === aiMessageId)
        if (aiMessage) {
          aiMessage.text = '抱歉，发生错误，请重新登录。'
          aiMessage.loading = false
        }
        this.isDoneInput = true

        // 显示提示并跳转到登录页
        uni.showToast({
          title: '登录已失效，请重新登录',
          icon: 'none',
          duration: 2000
        })
        
        // 清除用户信息并跳转登录
        setTimeout(() => {
          this.$store.commit('user/CLEAR_USER_INFO')
          this.$store.commit('token/CLEAR_TOKEN')
          uni.reLaunch({ url: '/subPages/auth/login' })
        }, 2000)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.page-box {
  height: calc(100vh - 186rpx);
  display: flex;
  flex-direction: column;

  &.page-no-btn {
    height: calc(100vh - 154rpx);
  }
}

.ai-content {
  flex: 1;
  padding: 32rpx;
  overflow-y: auto;
  /* 确保 scroll-view 可以滚动 */
  height: 0; /* 配合 flex:1 使用，让 scroll-view 有明确高度 */
  -webkit-overflow-scrolling: touch; /* iOS 平滑滚动 */
}

.ai-footer {
  background-color: #ffffff;
  padding: 16rpx 32rpx;
  position: fixed;
  bottom: 120rpx;
  box-sizing: border-box;
  width: 100%;
}

.short-buttons {
  width: 100%;
  display: flex;
  flex-wrap: nowrap;
  align-items: center;
  overflow-x: scroll;
  margin-bottom: 16rpx;

  &::-webkit-scrollbar {
    display: none;
  }
}

.ai-chat-composer {
  .composer-core {
    border-radius: 32rpx;
    background-color: #f8f9fa;
    border-color: #f8f9fa;
  }
}

.s-dialog {
  display: flex;
  justify-content: center;
  margin-top: 80rpx;
}

.message-box {
  display: flex;
  flex-direction: column;
  height: 100vh;

  .message-top {
    padding: 0rpx 0rpx 60rpx 0;
    overflow-y: auto;
    flex: 1;
    height: 0; /* 配合 flex:1 使用，让 scroll-view 有明确高度 */
    -webkit-overflow-scrolling: touch; /* iOS 平滑滚动 */
  }

  .message-list {
    .message-title {
      color: #333;
      font-size: 32rpx;
      margin-top: 40rpx;
      margin-bottom: 12rpx;
      padding-left: 28rpx;
      font-weight: bold;
    }

    .message-content {
      color: #333333;
      font-size: 32rpx;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      padding: 0rpx 32rpx;
      display: flex;
      align-items: center;
      height: 80rpx;

      text {
        flex: 1;
        white-space: nowrap;
        overflow: hidden;
        margin-right: 8rpx;
      }

      &.active {
        background: #e3e3e3;
        border-radius: 20rpx;
      }

      .edit-input {
        margin: 8rpx 0;

        :deep(.uv-input) {
          background-color: #f5f5f5;
          border-radius: 8rpx;
          padding: 8rpx 12rpx;
        }
      }
    }
  }
}

.setup-bot {
  border-top: 1rpx solid #ddd;
  padding: 0 40rpx 0rpx 40rpx;
  height: 144rpx;

  .setup-bot-box {
    display: flex;
    align-items: center;
    height: 140rpx;
  }

  .setup-userHeadImg {
    position: relative;
    margin-right: 20rpx;
    width: 68rpx;
    height: 68rpx;
    border-radius: 68rpx;
    border: 1rpx solid #ddd;
    display: flex;
    align-items: center;
    justify-content: center;

    image {
      width: 48rpx;
      height: 48rpx;
      display: block;
      border-radius: 48rpx;
    }
  }

  .setup-userName {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    flex: 1;
    color: #333;
    font-size: 32rpx;
  }
}

.setup-box {
  padding: 20rpx 0;

  .box-list {
    min-width: 200rpx;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    padding: 20rpx 40rpx;

    .setup-name {
      padding-left: 12rpx;
    }
  }
}
</style>
